window.YUI = window.YUI || {};

YUI.tabs = function(options) {
	this.init = function(options) {
		let me = this;
		me.options = options || {
			current: 0,
			head: null,
			body: null,
			active: "active",
			tabChanged: null
		};
		me.data = [];
		if (!me.options.current) {
			me.options.current = 0;
		}
		if (!me.options.active) {
			me.options.active = "active";
		}
		if (me.options.head) {
			$(me.options.head).children().click(function() {
				me.setCurrent($(this).index());
			});
		}
		me.setCurrent(me.options.current);
	};

	this.getCurrent = function() {
		return this.options.current;
	};

	this.getCurrentKey = function() {
		let index = this.getCurrent();
		if (this.options.head) {
			return $(this.options.head).children(":eq(" + index + ")").attr("data-key");
		}
		return null;
	};

	this.setCurrent = function(value) {
		let me = this;
		let total = $(me.options.head).children().length;
		if (value < 0) value = 0;
		if (value >= total) value = total - 1;
		if (value == -1) return;
		if (me.options.head) {
			$(me.options.head).children().removeClass(me.options.active);
			$(me.options.head).children(":eq(" + value + ")").addClass(me.options.active);
		}
		if (me.options.body) {
			$(me.options.body).children().removeClass(me.options.active).hide();
			$(me.options.body).children(":eq(" + value + ")").addClass(me.options.active).show();
		}
		this.options.current = value;
		if (me.options.tabChanged != null) {
			if (me.data[value] == null) {
				me.data[value] = {};
			}
			if (me.data[value].initial == null) {
				me.data[value].initial = true;
			} else {
				me.data[value].initial = false;
			}
			let key = me.getCurrentKey();
			me.options.tabChanged(value, me.data[value].initial, key);
		}
	};

	this.init(options);
}
